//require FingerprintScanner
package com.codename1.samples;


import com.codename1.components.ToastBar;
import com.codename1.fingerprint.Fingerprint;
import com.codename1.fingerprint.KeyRevokedException;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.ui.Button;
import com.codename1.ui.CN;
import com.codename1.ui.Command;
import com.codename1.ui.Container;
import com.codename1.ui.TextField;
import com.codename1.util.AsyncResource;

/**
 * This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose 
 * of building native mobile applications using Java.
 */
public class FingerprintScannerSample {

    private Form current;
    private Resources theme;

    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });        
    }
    
    public void start() {
        if(current != null){
            current.show();
            return;
        }
        Form hi = new Form("Hi World", BoxLayout.y());
        TextField keyName = new TextField();
        TextField keyValue = new TextField();
        
        Button addItem = new Button("Add Item");
        Button getItem = new Button("Get Item");
        Button deleteItem = new Button("Delete Item");
        Button checkAvailable = new Button("Check Available");
        checkAvailable.addActionListener(evt->{
            Container cnt = BoxLayout.encloseY(
                    new Label("TouchID: "+Fingerprint.isTouchIDAvailable()),
                    new Label("FaceID: "+Fingerprint.isFaceIDAvailable())
            );
            Dialog.show("Capabilities", cnt, new Command("OK"));
        });
        addItem.addActionListener(evt->{
            if (!Fingerprint.isAvailable()) {
                ToastBar.showErrorMessage("Fingerprint not avaiable on this platform");
                return;
            }
            Fingerprint.addPassword("Adding secure item to keystore", keyName.getText(), keyValue.getText()).onResult((res, err)->{
                if (err != null) {
                    if (AsyncResource.isCancelled(err)) {
                        Log.p("addPassword request was cancelled");
                        return;
                    }
                    Log.e(err);
                    ToastBar.showErrorMessage(err.getMessage());
                } else {
                    ToastBar.showInfoMessage("Result: "+res);
                }
            });
        });
        getItem.addActionListener(evt->{
            Fingerprint.getPassword("Getting secure item", keyName.getText()).onResult((res, err)->{
                if (err != null) {
                    if (AsyncResource.isCancelled(err)) {
                        Log.p("getPassword request was cancelled");
                        return;
                    }
                    Log.e(err);
                    if (err instanceof KeyRevokedException) {
                        ToastBar.showErrorMessage("Your key has been invalidated, likely due to adding new fingerprints");
                    } else {
                    
                        ToastBar.showErrorMessage(err.getMessage());
                    }
                } else {
                    keyValue.setText(res);
                    hi.revalidateWithAnimationSafety();
                }
            });
        });
        deleteItem.addActionListener(evt->{
            Fingerprint.deletePassword("Getting secure item", keyName.getText()).onResult((res, err)->{
                if (err != null) {
                    if (AsyncResource.isCancelled(err)) {
                        Log.p("deletePassword request was cancelled");
                    }
                    Log.e(err);
                    ToastBar.showErrorMessage(err.getMessage());
                } else {
                    keyValue.setText("");
                    hi.revalidateWithAnimationSafety();
                }
            });
        });
        
        Button checkHardware = new Button("Check Hardware");
        checkHardware.addActionListener(evt->{
            Fingerprint.isAvailable();
            Dialog.show("Hardware", CN.getProperty("Fingerprint.types", "None"), "OK", null);
        });
        
        
        
        hi.addAll(checkHardware, new Label("Key:"), keyName, new Label("Value: "), keyValue, addItem, getItem, deleteItem, checkAvailable);
        hi.show();
    }

    public void stop() {
        current = getCurrentForm();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = getCurrentForm();
        }
    }
    
    public void destroy() {
    }

}
